//
//  MineViewController.m
//  Delicious2
//
//  Created by FSD on 16/1/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MineViewController.h"
#import "MineTableViewCell.h"
#import "ShouCangViewController.h"
#import "NearFoodViewController.h"

#import <MessageUI/MessageUI.h>
@interface MineViewController ()<UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, retain) UISwitch *swt;
@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationItem.title = @"我的";
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    self.imageView.image = [UIImage imageNamed:@"headImage"];
    self.imageView.userInteractionEnabled = YES;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.image = [UIImage imageNamed:@"ImageTouXiang"];
    imageView.center = self.imageView.center;
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 50;
    imageView.userInteractionEnabled = YES;
    [self.imageView addSubview:imageView];
    
    self.swt = [[UISwitch alloc] initWithFrame:CGRectMake(0, 5, 60, 35)];
    [self.swt addTarget:self action:@selector(switchNight:) forControlEvents:UIControlEventValueChanged];

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[MineTableViewCell class] forCellReuseIdentifier:@"mineTableViewIdentifer"];
    self.tableView.tableHeaderView = self.imageView;
    [self.view addSubview:self.tableView];
    
    
//    通知   
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"changeColor" object:nil];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mineTableViewIdentifer"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    if ([passWord isEqualToString:@"Night"]) {
        cell.backgroundColor = [UIColor grayColor];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    if (indexPath.row == 0) {
        cell.mineLabel.text = @"我的收藏";
        cell.mineImage.image = [UIImage imageNamed:@"shouCang"];
        return cell;
    }
    else if (indexPath.row == 1) {
        cell.mineLabel.text = @"清除缓存";
        cell.mineImage.image = [UIImage imageNamed:@"clear"];
        return cell;
    }
    else if (indexPath.row == 2) {
        cell.mineLabel.text = @"意见反馈";
        cell.mineImage.image = [UIImage imageNamed:@"fankui"];
        return cell;
    }
    else if (indexPath.row == 3){
        cell.mineLabel.text = @"夜间模式";
        cell.mineImage.image = [UIImage imageNamed:@"night"];
        [cell.lastLabel addSubview:self.swt];
        return cell;
    } else {
        cell.mineLabel.text = @"附近美食";
        cell.mineImage.image = [UIImage imageNamed:@"ImageNearDingwei"];
        return cell;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        ShouCangViewController *shouCang = [[ShouCangViewController alloc] init];
        [self.navigationController pushViewController:shouCang animated:YES];
    } else if (indexPath.row == 1) {
 
        //计算缓存大小
        NSString *sandPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES)[0];
        float size = [self folderSizeAtPath:sandPath];
        NSString *str=[NSString stringWithFormat:@"确定清除%0.2fM缓存",size]; 

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];

    } else if (indexPath.row == 2) {

        BOOL canSendMail = [MFMailComposeViewController canSendMail];
        if (canSendMail) {
            MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
            picker.mailComposeDelegate = self;
            [picker setSubject:@"意见反馈"];
            [picker setToRecipients:@[@"food_library@boohee.com"]];
            [picker setCcRecipients:@[@"18643350351@163.com"]];
            [picker setMessageBody:@"" isHTML:YES];

            [self presentViewController:picker animated:YES completion:nil];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请提前登陆邮箱" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    } else if(indexPath.row == 4) {
        NearFoodViewController *nearfoodVC = [[NearFoodViewController alloc] init];
        
        [self.navigationController pushViewController:nearfoodVC animated:YES];
    }
    
}

#pragma mark ---- 夜间模式开关时间
-(void)switchNight:(UISwitch *)send {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    if ([passWord isEqualToString:@"Night"]) {
        [user setObject:@"Day" forKey:@"NightMode"];
    } else {
        [user setObject:@"Night" forKey:@"NightMode"];
    }
    [self.view nightMode];
    [self.imageView nightMode];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"changeColor" object:@"Night" userInfo:nil];
//    [self.tableView nightMode];
//    [self.tableView reloadData];
    //    通知
}

#pragma mark ----- 夜间模式改变颜色方法
-(void)receiveNotification:(NSNotification *)sender {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *mode = [user objectForKey:@"NightMode"];
    
    if ([mode isEqualToString:@"Night"]) {
        self.tableView.backgroundColor = [UIColor grayColor];
        self.navigationController.navigationBar.barTintColor = [UIColor grayColor];
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = kColor;
    }
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *mode = [user objectForKey:@"NightMode"];
    
    if ([mode isEqualToString:@"Night"]) {
        self.swt.on = YES;
    } else {
        self.swt.on = NO;
    }
    [super viewWillAppear:YES];
    [self.view nightMode];
    [self.imageView nightMode];
    [self.tableView nightMode];
    [self.tableView reloadData];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex) {
        
        //      清除缓存
        NSFileManager *manager=[NSFileManager defaultManager];
        NSString *sandPath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES)[0];
        
        if ([manager fileExistsAtPath:sandPath]) {
            NSArray *childerFiles=[manager subpathsAtPath:sandPath];
            
            for (NSString *fileName in childerFiles) {
                //如有需要，加入条件，过滤掉不想删除的文件
                NSString *absolutePath=[sandPath stringByAppendingPathComponent:fileName];
                [manager removeItemAtPath:absolutePath error:nil];
            }
        }
        
        [[SDImageCache sharedImageCache] clearDisk];
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.mode = MBProgressHUDModeText;
        HUD.yOffset = HEIGHT / 3;
        HUD.margin = 5;
        HUD.cornerRadius = 5;
        HUD.labelText = @"已清除缓存";
        [HUD hide:YES afterDelay:1];
        [self.tableView reloadData];
        
        alertView.hidden = YES;
    }
}

#pragma mark -- 计算文件大小
- (float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }
    //根据路径获取文件夹里面元素集合
    //获取集合类型的枚举类型
    NSEnumerator *enumeratot = [[manager subpathsAtPath:path] objectEnumerator];
    //每次遍历得到的文件名
    //文件夹的大小
    NSString *fileName = [NSString string];
    float folderSize = 0;
    while ((fileName = [enumeratot nextObject])!= nil) {
        NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:absolutePath];
    }
    return folderSize/(1024*1024.0);
}

- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil]fileSize];
    }
    return 0;
}

//邮件协议方法
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText;
    HUD.yOffset = HEIGHT / 3;
    HUD.margin = 5;
    HUD.cornerRadius = 5;
    
    switch (result) {
        case MessageComposeResultCancelled:
            HUD.labelText = @"取消发送";
            [HUD hide:YES afterDelay:2];
            break;
        case MessageComposeResultSent:
            HUD.labelText = @"发送成功";
            [HUD hide:YES afterDelay:2];
            break;
        case MessageComposeResultFailed:
            HUD.labelText = @"发送成功";
            [HUD hide:YES afterDelay:2];
            break;
            
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
